package com.d.client;

import com.d.client.dto.DingAppAccessTokenDto;
import com.d.common.utils.RedisUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiFileUploadSingleRequest;
import com.dingtalk.api.request.OapiMediaUploadRequest;
import com.dingtalk.api.response.OapiFileUploadSingleResponse;
import com.dingtalk.api.response.OapiMediaUploadResponse;
import com.dtflys.forest.utils.StringUtils;
import com.taobao.api.ApiException;
import com.taobao.api.FileItem;
import com.taobao.api.internal.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class DingFileClient {

    @Autowired
    private DingClient dingClient;

    @Value("${forest.variables.dingAppKey}")
    String dingAppKey;
    @Value("${forest.variables.dingAppSecret}")
    String dingAppSecret;

    private String REDIS_TOKEN_CACHE_KEY = "ding_token_" + dingAppKey;

    private String token() {
        String token;
        if (StringUtils.isEmpty(RedisUtil.getJedisVal(REDIS_TOKEN_CACHE_KEY + dingAppKey))) {
            DingAppAccessTokenDto tokenDto = dingClient.getAppToken(dingAppKey, dingAppSecret);
            token = tokenDto.getAccessToken();
            RedisUtil.setJedisVal(REDIS_TOKEN_CACHE_KEY + dingAppKey, tokenDto.getAccessToken(), tokenDto.getExpireIn().intValue());
        } else {
            token = RedisUtil.getJedisVal(REDIS_TOKEN_CACHE_KEY + dingAppKey);
        }
        return token;
    }


    /**
     * dingpan
     * 单步文件上传
     *
     * @param
     * @return
     */
    public String upload(String filePath) {
        try {
            OapiFileUploadSingleRequest request = new OapiFileUploadSingleRequest();
            request.setFileSize(45L);
            request.setAgentId("83642");
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/file/upload/single?" + WebUtils.buildQuery(request.getTextParams(), "utf-8"));
            // 必须重新new一个请求
            request = new OapiFileUploadSingleRequest();
            request.setFile(new FileItem(filePath));
            OapiFileUploadSingleResponse response = null;
            response = client.execute(request, this.token());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ApiException e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * ding多媒体上传文件
     *
     * @param type     image：图片，图片最大20MB。支持上传jpg、gif、png、bmp格式。
     *                 voice：语音，语音文件最大2MB。支持上传amr、mp3、wav格式。
     *                 video：视频，视频最大20MB。支持上传mp4格式。
     *                 file：普通文件，最大20MB。支持上传doc、docx、xls、xlsx、ppt、pptx、zip、pdf、rar格式。
     * @param filePath
     * @return
     */
    public String media(String type, String filePath) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/media/upload");
            OapiMediaUploadRequest req = new OapiMediaUploadRequest();
            req.setType(type);
            // 要上传的媒体文件
            FileItem item = new FileItem(filePath);
            req.setMedia(item);
            OapiMediaUploadResponse rsp = client.execute(req, this.token());
            System.out.println(rsp.toString());
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

}
